<?php
/******************************************************************************
    NuCMS Framework, for the quick deployment of applications developed in
    php.
    Copyright (C) 2009  Matthew General

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
******************************************************************************/
/**
 * 
 * @author mgeneral
 *
 */
class TemplateManager extends Debug{
	/**
	 * 
	 * @var unknown_type
	 */
	private $_data;
	
	/**
	 * 
	 * @var unknown_type
	 */
	private $_template;
	
	/**
	 * 
	 */
	private $_templateName;
	/**
	 * 
	 * @param $file
	 * @return unknown_type
	 */
	public function __construct($file="Config/config.ini") {
		parent::__construct($file);
		unset($this->_settings["database"]);//security
		
	}
	
	/**
	 * 
	 * @return unknown_type
	 */
	public function loadTemplate() {
		$this->debugMessage(self::DEBUG_ALL,"**Loading template at ".$this->_settings["all"]["appPath"].$this->_settings["template"]["directory"].$this->_templateName."/"."main.tpl");
		if(file_exists($this->_settings["all"]["appPath"].$this->_settings["template"]["directory"].$this->_templateName."/"."main.tpl")) {
			$this->_template = file_get_contents($this->_settings["all"]["appPath"].$this->_settings["template"]["directory"].$this->_templateName."/"."main.tpl");
			$this->loadIncludes();
		}else {
			if(file_exists($this->_settings["all"]["appPath"].$this->_settings["template"]["directory"]."default/main.tpl")) {
				$this->_template = file_get_contents($this->_settings["all"]["appPath"].$this->_settings["template"]["directory"]."default/main.tpl");
				$this->loadIncludes();
			}else {
				throw new Error("Main template does not exist. Searching for ".$this->_settings["all"]["appPath"].$this->_settings["template"]["directory"].$this->_templateName."/main.tpl or ".$this->_settings["all"]["appPath"].$this->_settings["template"]["directory"]."default/main.tpl");
			}
		}
	}
	
	/**
	 * 
	 * @param $data
	 * @param $expedite
	 * @return unknown_type
	 */
	public function update($data) {
		$this->debugMessage(self::DEBUG_ALL,"Template update with ".print_r($data,true));
		foreach($data as $key => $val) {
			if($this->_data[$key])
				throw new Error("update attempting to rewrite template data!");
			$this->_data[$key]=$val;	
		}
	}
	
	/**
	 * 
	 * @return unknown_type
	 */
	public function output() {
		try {
			$this->updateTemplate($this->_data);
		}catch(Error $e) {
			echo $e;
		}
		echo $this->_template;
	}
	
	/**
	 * 
	 * @param $name
	 * @return unknown_type
	 */
	public function setTemplateName($name) {
		$this->debugMessage(self::DEBUG_ALL,"Template Name set to ".$name);
		$this->_templateName=$name;
		$this->loadTemplate();
	}
	/**
	 * 
	 * @param $data
	 * @return unknown_type
	 */
	private function updateTemplate($data) {
		if($data) {
			foreach($data as $key => $val) {
				if(false==strpos($this->_template,"{{".$key."}}")) {
					throw new Error("no key in template for ".$key);
				}else{
					//needs to be in form of array(array('key'=>'val'),array('key'=>'val'));
					if(!is_array($val))
						$this->_template=str_replace("{{".$key."}}",$val,$this->_template);
					else{
						//load template for the repetitive data and replace foreach key in the array
						$string='';
						foreach($val as $row) {
							if(is_array($val)) {
								if(file_exists($this->_settings["all"]["appPath"].$this->_settings["template"]["directory"].$this->_templateName."/".$key.".tpl")){
									$string.=file_get_contents($this->_settings["all"]["appPath"].$this->_settings["template"]["directory"].$this->_templateName."/".$key.".tpl");
									foreach($row as $k=>$v) {
										$string = str_replace("{{".$k."}}",$v,$string);
									}
								}else {
									if(file_exists($this->_settings["all"]["appPath"].$this->_settings["template"]["directory"]."default/".$key.".tpl")){
										$string.=file_get_contents($this->_settings["all"]["appPath"].$this->_settings["template"]["directory"]."default/".$key.".tpl");
										foreach($row as $k=>$v) {
											$string = str_replace("{{".$k."}}",$v,$string);
										}
										
									}else {
										throw new Error("Template does not exist! Searching for ".$this->_settings["all"]["appPath"].$this->_settings["template"]["directory"]."default/".$key.".tpl");
									}
								}
							}
						}
						$this->_template=str_replace("{{".$key."}}",$string,$this->_template);
						
					}
				}
			}
		}
	}
	
	/**
	 * 
	 * @return unknown_type
	 */
	private function loadIncludes() {
		preg_match('#\{\{\:[A-Za-z0-9_]+\:\}\}#u',$this->_template,$includes);
		$this->debugMessage(self::DEBUG_ALL,"Searching template for includes. Found ".print_r($includes,true));
		$this->debugMessage(self::DEBUG_ALL,"Including template peices ".$this->_templateName." being used");
		$this->debugMessage(self::DEBUG_ALL,"Number of peices found: ".count($includes));
		foreach($includes as $include) {
			$this->debugMessage(self::DEBUG_ALL,"Loading include ".$this->_settings["all"]["appPath"].$this->_settings["template"]["directory"].$this->_templateName."/".substr($include,3,strlen($include)-6).".tpl");
			if(file_exists($this->_settings["all"]["appPath"].$this->_settings["template"]["directory"].$this->_templateName."/".substr($include,3,strlen($include)-6).".tpl")){
				$this->_template=str_replace($include,file_get_contents($this->_settings["all"]["appPath"].$this->_settings["template"]["directory"].$this->_templateName."/".substr($include,3,strlen($include)-6).".tpl"),$this->_template);
			}
			else{
				if(file_exists($this->_settings["all"]["appPath"].$this->_settings["template"]["directory"]."default/".substr($include,3,strlen($include)-6)).".tpl") {
					$this->_template=str_replace($include,file_get_contents($this->_settings["all"]["appPath"].$this->_settings["template"]["directory"]."default/".substr($include,3,strlen($include)-6).".tpl"),$this->_template);
				}
				else{
					throw new Error("Template does not exist! Searching for ".$this->_settings["all"]["appPath"].$this->_settings["template"]["directory"].$this->_templateName."/".substr($include,3,strlen($include)-6).".tpl");
				}
			}
		}
		if(count($includes)>0) $this->loadIncludes();
	}
}
?>